<?php
// +----------------------------------------------------------------------
// | SparkERP 优秀的进销存系统
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2099 http://erp.sparkshop.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai  <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\service;

use app\model\setting\AdminNode;
use app\model\setting\AdminRole;
use app\model\setting\AdminUser;
use app\validate\LoginValidate;
use think\exception\ValidateException;
use utils\Captcha;

class LoginService
{
    /**
     * 处理登陆
     * @param array $param
     * @return array
     */
    public function doLogin(array $param) : array
    {
        try {
            validate(LoginValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-1, $e->getError());
        }

        // 验证码
       /* $captcha = new Captcha();
        if (!$captcha->check($param['captcha'], $param['key'])) {
            return dataReturn(-5, '验证码错误');
        }*/

        $userModel = new AdminUser();
        $userInfo = $userModel->findOne([
            'name' => $param['username']
        ])['data'];

        if (empty($userInfo)) {
            return dataReturn(-2, '用户名密码错误');
        }

        if ($userInfo['password'] != makePassword($param['password'], $userInfo['salt'])) {
            return dataReturn(-3, '用户名密码错误');
        }

        if ($userInfo['status'] == 2) {
            return dataReturn(-4, '您已被禁用');
        }

        $authNode = [];
        $authMenu = [];
        $adminNodeModel = new AdminNode();
        $field = 'id,pid,name,auth,path,icon,component,hidden,is_menu';

        // 角色信息
        if ($userInfo['role_id'] != 1) {

            $roleModel = new AdminRole();
            $roleInfo = $roleModel->findOne([
                'id' => $userInfo['role_id']
            ])['data'];

            if ($roleInfo['status'] == 2) {
                return dataReturn(-5, '您的账号角色被禁用');
            }

            $nodeList = $adminNodeModel->field($field)->where('status', 1)
                ->whereIn('id', explode(',', $roleInfo['role_node']))->order('sort desc')->select();
            if (!empty($nodeList)) {
                $nodeList = $nodeList->toArray();
            }

            foreach ($nodeList as $vo) {
                $authNode[$vo['auth']] = 1;

                if ($vo['is_menu'] == 2) {
                    $authMenu[] = $vo;
                }
            }

            // 记录权限map后续校验用
            cache($userInfo['id'] . '_auth_node', $authNode);
        } else {

            $authMenu = $adminNodeModel->field($field)
                ->where('status', 1)->where('is_menu', 2)->order('sort desc')->select()->toArray();
        }

        foreach ($authMenu as $key => $vo) {
            $authMenu[$key]['meta'] = [
                'icon' => $vo['icon'],
                'title' => $vo['name'],
                'type' => 'menu',
                'hidden' => $vo['hidden'] == 1
            ];
            // 确保名称唯一
            $authMenu[$key]['name'] = $vo['name'] . $vo['path'];

            if ($vo['pid'] == 0) {
                unset($authMenu[$key]['component']);
            }
        }

        // 权限菜单
        $authMenu = makeTree($authMenu);

        $updateParam = [
            'last_login_ip' => request()->ip(),
            'last_login_time' => now(),
            'last_login_agent' => request()->header()['user-agent']
        ];

        $userModel->updateById($updateParam, $userInfo['id']);

        $token = setJWT([
            'id' => $userInfo['id'],
            'role_id' => $userInfo['role_id'],
            'nickname' => $userInfo['nickname'],
            'avatar' => $userInfo['avatar'],
            'code' => $userInfo['code']
        ]);

        return dataReturn(0, '登录成功', [
            'userInfo' => [
                'id' => $userInfo['id'],
                'role_id' => $userInfo['role_id'],
                'userName' => $userInfo['nickname'],
                'avatar' => $userInfo['avatar'],
                'code' => $userInfo['code']
            ],
            'token' => $token,
            'menu' => $authMenu
        ]);
    }
}